import Vue from 'vue';
import axios from 'axios';
import { Notify } from 'quasar';

const info = (msg) => Notify.create({
  color: 'green',
  position: 'top',
  message: msg,
});

const error = (msg) => Notify.create({
  color: 'red',
  position: 'top',
  message: msg,
});
axios.interceptors.request.use((config) => {
  const token = localStorage.Authorization;
  if (token) { config.headers.Authorization = token; }
  return config;
});
export const needLoginCode = [401, 402, 403];

export const goLogin = () => {
  if (!window.location.pathname.startsWith('/login')) {
    delete localStorage.Authorization;
    setTimeout(() => {
      window.location.replace(`/login/${encodeURIComponent(
        window.location.pathname + window.location.search + window.location.hash,
      )}`);
    });
  }
};

axios.interceptors.response.use(
  (r) => {
    if (r.data) {
      if (r.data.code && r.data.code !== 200) {
        if (r.data.message) {
          error(`${r.data.code} - ${r.data.message}`);
        }
        if (needLoginCode.some((v) => v === r.data.code)) {
          goLogin();
        }
        return Promise.reject(r);
      }
      return r.data;
    }
    return r;
  },
  ({ response }) => {
    let msg = '未知错误';
    if (response) {
      if (response.data) {
        if (!response.data.status) {
          msg = '服务器正在重启或者已经挂了！';
        } else {
          msg = `${response.data.status} - ${response.data.message}`;
        }
      } else {
        msg = `${response.status} - `;
        switch (response.status) {
          case -1:
            msg += '连接失败';
            break;
          case 500:
            msg += '内部错误';
            break;
          case 404:
            msg += '页面不存在';
            break;
          case 401:
          case 402:
          case 403:
            msg += '权限不足';
            goLogin();
            break;
          default:
            msg += '未知错误';
        }
      }
    }
    error(msg);
    return Promise.reject(response);
  },
);
Vue.prototype.$axios = axios;
Vue.prototype.$info = info;
Vue.prototype.$error = error;
